<template>
  <div class="profit-statement-container">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>银杏ERP</el-breadcrumb-item>
      <el-breadcrumb-item>财务管理</el-breadcrumb-item>
      <el-breadcrumb-item>利润表</el-breadcrumb-item>
    </el-breadcrumb>
    
    <el-card class="filter-card">
      <div class="filter-header">
        <div class="filter-title">查询条件</div>
        <div class="filter-actions">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleExport">导出</el-button>
          <el-button type="warning" @click="handlePrint">打印</el-button>
        </div>
      </div>
      
      <el-form :model="filterForm" ref="filterFormRef" label-width="80px" class="filter-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="日期类型">
              <el-select v-model="filterForm.dateType" placeholder="请选择日期类型" style="width: 100%">
                <el-option label="月度" value="month"></el-option>
                <el-option label="季度" value="quarter"></el-option>
                <el-option label="年度" value="year"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="6">
            <el-form-item label="起始日期">
              <el-date-picker 
                v-model="filterForm.startDate" 
                :type="getDatePickerType()" 
                placeholder="请选择起始日期"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          
          <el-col :span="6">
            <el-form-item label="结束日期">
              <el-date-picker 
                v-model="filterForm.endDate" 
                :type="getDatePickerType()" 
                placeholder="请选择结束日期"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          
          <el-col :span="6">
            <el-form-item label="对比">
              <el-switch v-model="filterForm.enableComparison"></el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20" v-if="filterForm.enableComparison">
          <el-col :span="6">
            <el-form-item label="对比类型">
              <el-select v-model="filterForm.comparisonType" placeholder="请选择对比类型" style="width: 100%">
                <el-option label="上期" value="prev"></el-option>
                <el-option label="去年同期" value="prevYear"></el-option>
                <el-option label="自定义" value="custom"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="6" v-if="filterForm.comparisonType === 'custom'">
            <el-form-item label="对比起始">
              <el-date-picker 
                v-model="filterForm.comparisonStartDate" 
                :type="getDatePickerType()" 
                placeholder="请选择对比起始日期"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          
          <el-col :span="6" v-if="filterForm.comparisonType === 'custom'">
            <el-form-item label="对比结束">
              <el-date-picker 
                v-model="filterForm.comparisonEndDate" 
                :type="getDatePickerType()" 
                placeholder="请选择对比结束日期"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    
    <el-row :gutter="20" class="summary-row">
      <el-col :span="6" v-for="(card, index) in summaryCards" :key="index">
        <el-card class="summary-card">
          <div class="summary-content">
            <div class="summary-label">{{ card.label }}</div>
            <div class="summary-value">{{ card.value }}</div>
            <div class="summary-trend" v-if="card.trend !== undefined" :class="card.trend > 0 ? 'trend-up' : 'trend-down'">
              <el-icon>
                <component :is="card.trend > 0 ? 'ArrowUp' : 'ArrowDown'"></component>
              </el-icon>
              <span>{{ Math.abs(card.trend) }}% {{ card.trend > 0 ? '增长' : '下降' }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-card class="profit-statement-card">
      <template #header>
        <div class="card-header">
          <div class="header-title">利润表明细</div>
          <div class="header-actions">
            <el-dropdown>
              <el-button size="small">
                展示形式
                <el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="setDisplayMode('list')">表格式</el-dropdown-item>
                  <el-dropdown-item @click="setDisplayMode('tree')">树形式</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </template>
      
      <div v-if="displayMode === 'list'">
        <el-table
          :data="profitStatementData"
          style="width: 100%"
          border
          row-key="id"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        >
          <el-table-column prop="name" label="项目" width="250"></el-table-column>
          <el-table-column prop="formula" label="计算公式" width="200"></el-table-column>
          <el-table-column prop="currentAmount" label="本期金额" width="200">
            <template #default="scope">
              <span :class="getAmountClass(scope.row.currentAmount)">{{ formatAmount(scope.row.currentAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="filterForm.enableComparison" prop="comparisonAmount" label="对比期金额" width="200">
            <template #default="scope">
              <span :class="getAmountClass(scope.row.comparisonAmount)">{{ formatAmount(scope.row.comparisonAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="filterForm.enableComparison" label="增减变动" width="150">
            <template #default="scope">
              <span :class="getVarianceClass(scope.row)">{{ formatVariance(scope.row) }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="filterForm.enableComparison" label="变动率" width="120">
            <template #default="scope">
              <span :class="getVarianceRateClass(scope.row)">{{ formatVarianceRate(scope.row) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注"></el-table-column>
        </el-table>
      </div>
      
      <div v-else class="tree-view">
        <el-scrollbar height="650px">
          <el-tree
            :data="profitStatementTreeData"
            node-key="id"
            default-expand-all
            :expand-on-click-node="false"
          >
            <template #default="{ node, data }">
              <div class="custom-tree-node">
                <div class="tree-item-left">
                  <span class="tree-item-name">{{ data.name }}</span>
                  <span class="tree-item-formula" v-if="data.formula">{{ data.formula }}</span>
                </div>
                <div class="tree-item-right">
                  <div class="tree-item-amount">
                    <span class="amount-label">本期:</span>
                    <span :class="getAmountClass(data.currentAmount)">{{ formatAmount(data.currentAmount) }}</span>
                  </div>
                  <div class="tree-item-amount" v-if="filterForm.enableComparison">
                    <span class="amount-label">对比期:</span>
                    <span :class="getAmountClass(data.comparisonAmount)">{{ formatAmount(data.comparisonAmount) }}</span>
                  </div>
                  <div class="tree-item-amount" v-if="filterForm.enableComparison">
                    <span class="amount-label">变动:</span>
                    <span :class="getVarianceClass(data)">{{ formatVariance(data) }} ({{ formatVarianceRate(data) }})</span>
                  </div>
                </div>
              </div>
            </template>
          </el-tree>
        </el-scrollbar>
      </div>
    </el-card>
    
    <el-card class="profit-statement-chart-card" v-if="filterForm.dateType !== 'year'">
      <template #header>
        <div class="card-header">
          <div class="header-title">利润趋势图</div>
          <div class="header-actions">
            <el-select v-model="chartType" size="small">
              <el-option label="柱状图" value="bar"></el-option>
              <el-option label="折线图" value="line"></el-option>
              <el-option label="组合图" value="mixed"></el-option>
            </el-select>
          </div>
        </div>
      </template>
      
      <div class="chart-container">
        <ProfitTrendChart 
          :chartData="profitTrendData" 
          :chartType="chartType"
          :enableComparison="filterForm.enableComparison"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ArrowDown, ArrowUp } from '@element-plus/icons-vue'
import ProfitTrendChart from './components/ProfitTrendChart.vue'
import { ElMessage } from 'element-plus'

// 筛选表单
const filterForm = ref({
  dateType: 'month',
  startDate: new Date(new Date().getFullYear(), new Date().getMonth() - 5, 1),
  endDate: new Date(new Date().getFullYear(), new Date().getMonth(), 0),
  enableComparison: true,
  comparisonType: 'prevYear',
  comparisonStartDate: null,
  comparisonEndDate: null
})

const filterFormRef = ref(null)

// 获取日期选择器类型
const getDatePickerType = () => {
  switch (filterForm.value.dateType) {
    case 'month':
      return 'month'
    case 'quarter':
      return 'month'
    case 'year':
      return 'year'
    default:
      return 'month'
  }
}

// 搜索和重置
const handleSearch = () => {
  ElMessage.success('查询成功')
  // 这里应该调用API获取数据
}

const handleReset = () => {
  filterFormRef.value?.resetFields()
}

const handleExport = () => {
  ElMessage.success('导出成功')
}

const handlePrint = () => {
  window.print()
}

// 总览卡片数据
const summaryCards = ref([
  {
    label: '营业收入',
    value: '¥ 2,846,750.00',
    trend: 8.6
  },
  {
    label: '营业成本',
    value: '¥ 1,678,240.00',
    trend: 5.2
  },
  {
    label: '毛利润',
    value: '¥ 1,168,510.00',
    trend: 12.4
  },
  {
    label: '净利润',
    value: '¥ 548,320.00',
    trend: 18.7
  }
])

// 利润表数据
const profitStatementData = ref([
  {
    id: 1,
    name: '一、营业收入',
    formula: '',
    currentAmount: 2846750,
    comparisonAmount: 2621500,
    remark: '',
    children: [
      {
        id: 101,
        name: '主营业务收入',
        formula: '',
        currentAmount: 2723400,
        comparisonAmount: 2510000,
        remark: ''
      },
      {
        id: 102,
        name: '其他业务收入',
        formula: '',
        currentAmount: 123350,
        comparisonAmount: 111500,
        remark: ''
      }
    ]
  },
  {
    id: 2,
    name: '二、营业成本',
    formula: '',
    currentAmount: 1678240,
    comparisonAmount: 1595200,
    remark: '',
    children: [
      {
        id: 201,
        name: '主营业务成本',
        formula: '',
        currentAmount: 1592800,
        comparisonAmount: 1518500,
        remark: ''
      },
      {
        id: 202,
        name: '其他业务成本',
        formula: '',
        currentAmount: 85440,
        comparisonAmount: 76700,
        remark: ''
      }
    ]
  },
  {
    id: 3,
    name: '三、毛利润',
    formula: '一 - 二',
    currentAmount: 1168510,
    comparisonAmount: 1026300,
    remark: '',
  },
  {
    id: 4,
    name: '四、营业税金及附加',
    formula: '',
    currentAmount: 85402,
    comparisonAmount: 78645,
    remark: '',
  },
  {
    id: 5,
    name: '五、期间费用',
    formula: '',
    currentAmount: 424600,
    comparisonAmount: 398200,
    remark: '',
    children: [
      {
        id: 501,
        name: '销售费用',
        formula: '',
        currentAmount: 182500,
        comparisonAmount: 176200,
        remark: ''
      },
      {
        id: 502,
        name: '管理费用',
        formula: '',
        currentAmount: 156400,
        comparisonAmount: 148000,
        remark: ''
      },
      {
        id: 503,
        name: '研发费用',
        formula: '',
        currentAmount: 63500,
        comparisonAmount: 52800,
        remark: ''
      },
      {
        id: 504,
        name: '财务费用',
        formula: '',
        currentAmount: 22200,
        comparisonAmount: 21200,
        remark: ''
      }
    ]
  },
  {
    id: 6,
    name: '六、营业利润',
    formula: '三 - 四 - 五',
    currentAmount: 658508,
    comparisonAmount: 549455,
    remark: '',
  },
  {
    id: 7,
    name: '七、营业外收支净额',
    formula: '',
    currentAmount: 15200,
    comparisonAmount: 12800,
    remark: '',
    children: [
      {
        id: 701,
        name: '营业外收入',
        formula: '',
        currentAmount: 18600,
        comparisonAmount: 15400,
        remark: ''
      },
      {
        id: 702,
        name: '营业外支出',
        formula: '',
        currentAmount: 3400,
        comparisonAmount: 2600,
        remark: ''
      }
    ]
  },
  {
    id: 8,
    name: '八、利润总额',
    formula: '六 + 七',
    currentAmount: 673708,
    comparisonAmount: 562255,
    remark: '',
  },
  {
    id: 9,
    name: '九、所得税费用',
    formula: '',
    currentAmount: 125388,
    comparisonAmount: 100206,
    remark: '',
  },
  {
    id: 10,
    name: '十、净利润',
    formula: '八 - 九',
    currentAmount: 548320,
    comparisonAmount: 462049,
    remark: '',
  }
])

const profitStatementTreeData = computed(() => {
  return profitStatementData.value
})

// 展示形式
const displayMode = ref('list')

const setDisplayMode = (mode: string) => {
  displayMode.value = mode
}

// 金额和变动格式化
const formatAmount = (amount: number) => {
  return '¥ ' + amount.toLocaleString()
}

const getAmountClass = (amount: number) => {
  if (amount > 0) return 'amount-positive'
  if (amount < 0) return 'amount-negative'
  return ''
}

const formatVariance = (row: any) => {
  const variance = row.currentAmount - row.comparisonAmount
  const prefix = variance > 0 ? '+' : ''
  return prefix + variance.toLocaleString()
}

const getVarianceClass = (row: any) => {
  const variance = row.currentAmount - row.comparisonAmount
  if (variance > 0) return 'variance-up'
  if (variance < 0) return 'variance-down'
  return ''
}

const formatVarianceRate = (row: any) => {
  if (!row.comparisonAmount) return '-'
  const rate = (row.currentAmount - row.comparisonAmount) / Math.abs(row.comparisonAmount) * 100
  const prefix = rate > 0 ? '+' : ''
  return prefix + rate.toFixed(2) + '%'
}

const getVarianceRateClass = (row: any) => {
  if (!row.comparisonAmount) return ''
  const rate = (row.currentAmount - row.comparisonAmount) / Math.abs(row.comparisonAmount) * 100
  if (rate > 0) return 'variance-up'
  if (rate < 0) return 'variance-down'
  return ''
}

// 图表类型
const chartType = ref('mixed')

// 趋势图数据
const profitTrendData = ref({
  months: ['2023-11', '2023-12', '2024-01', '2024-02', '2024-03', '2024-04'],
  revenue: [2185000, 2320000, 2450000, 2380000, 2620000, 2846750],
  cost: [1350000, 1420000, 1480000, 1430000, 1560000, 1678240],
  profit: [458000, 492000, 520000, 502000, 530000, 548320],
  comparisonRevenue: [2050000, 2180000, 2300000, 2250000, 2400000, 2621500],
  comparisonCost: [1300000, 1370000, 1420000, 1380000, 1490000, 1595200],
  comparisonProfit: [390000, 420000, 450000, 435000, 448000, 462049]
})

onMounted(() => {
  // 这里可以调用API初始加载数据
  console.log('利润表页面加载完成')
})
</script>

<style scoped lang="scss">
.profit-statement-container {
  padding: 20px;
  
  .el-breadcrumb {
    margin-bottom: 20px;
  }
  
  .filter-card {
    margin-bottom: 20px;
    
    .filter-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      
      .filter-title {
        font-size: 16px;
        font-weight: 500;
        color: #303133;
      }
      
      .filter-actions {
        display: flex;
        gap: 10px;
      }
    }
  }
  
  .summary-row {
    margin-bottom: 20px;
    
    .summary-card {
      margin-bottom: 20px;
      border-radius: 8px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
      
      .summary-content {
        padding: 10px;
        
        .summary-label {
          font-size: 14px;
          color: #606266;
          margin-bottom: 10px;
        }
        
        .summary-value {
          font-size: 22px;
          font-weight: 600;
          color: #303133;
          margin-bottom: 8px;
        }
        
        .summary-trend {
          display: flex;
          align-items: center;
          font-size: 12px;
          
          .el-icon {
            margin-right: 4px;
          }
          
          &.trend-up {
            color: #67c23a;
          }
          
          &.trend-down {
            color: #f56c6c;
          }
        }
      }
    }
  }
  
  .profit-statement-card, .profit-statement-chart-card {
    margin-bottom: 20px;
    border-radius: 8px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-title {
        font-size: 16px;
        font-weight: 500;
        color: #303133;
      }
    }
  }
  
  .tree-view {
    margin-top: 10px;
    
    .custom-tree-node {
      display: flex;
      justify-content: space-between;
      width: 100%;
      padding-right: 20px;
      
      .tree-item-left {
        display: flex;
        align-items: center;
        gap: 10px;
        
        .tree-item-name {
          font-weight: 500;
        }
        
        .tree-item-formula {
          color: #909399;
          font-size: 12px;
        }
      }
      
      .tree-item-right {
        display: flex;
        gap: 20px;
        
        .tree-item-amount {
          display: flex;
          align-items: center;
          gap: 5px;
          min-width: 180px;
          
          .amount-label {
            color: #909399;
            font-size: 13px;
          }
        }
      }
    }
  }
  
  .chart-container {
    height: 350px;
    width: 100%;
  }
  
  .amount-positive {
    color: #67c23a;
  }
  
  .amount-negative {
    color: #f56c6c;
  }
  
  .variance-up {
    color: #67c23a;
  }
  
  .variance-down {
    color: #f56c6c;
  }
  
  @media print {
    .filter-card, .profit-statement-chart-card {
      display: none;
    }
  }
}

@media (max-width: 768px) {
  .filter-header {
    flex-direction: column;
    align-items: flex-start !important;
    
    .filter-actions {
      margin-top: 10px;
    }
  }
  
  .tree-view {
    .custom-tree-node {
      flex-direction: column;
      align-items: flex-start;
      
      .tree-item-right {
        margin-top: 8px;
        flex-direction: column;
        gap: 5px;
      }
    }
  }
}
</style> 